package com.example.userclient.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.userclient.BookRemark
import com.example.userclient.Main.ClientInfoHolder
import com.example.userclient.activity.MessageKey
import com.example.userclient.R
import com.example.userclient.databinding.MsgItemBinding

object MsgListAdapter : RecyclerView.Adapter<MsgListAdapter.ViewHolder>() {
    var dataSet: MutableMap<MessageKey,MutableList<BookRemark> >? = null


    class ViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {

        private val mBinding: MsgItemBinding? = DataBindingUtil.bind(view)

        fun changeData(bookRemark: BookRemark) {
            if (mBinding != null) {

                val bookRemark2 =  BookRemark()
                bookRemark2.id = bookRemark.id
                if(ClientInfoHolder.phone == bookRemark.sendFrom){
                    bookRemark2.sendFrom = "用户: "+ bookRemark.sendTo.replaceRange(3,7,"****")
                }else{
                    bookRemark2.sendFrom = "用户: "+ bookRemark.sendFrom.replaceRange(3,7,"****")
                }

                bookRemark2.content = "最新消息: "+ bookRemark.content
                bookRemark2.isRead = bookRemark.isRead
                mBinding.phone = bookRemark.sendFrom
                mBinding.msg = bookRemark2
                for(  i in ClientInfoHolder.liveBook!!){
                    if (i.id == bookRemark.book_id){
                        mBinding.book = i
//                        Log.i("Msg",mBinding.book?.picture!!)
                        break
                    }
                }


                Log.i("MsgListAdapter", "changeData")
            }
        }
    }

    private var listener: OnItemClickListener?= null
    interface OnItemClickListener {
        fun onItemClick(itemView: View?, position: Int)
    }
    fun setOnItemClickListener(listener: OnItemClickListener?) {
        MsgListAdapter.listener = listener
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.msg_item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        dataSet?.values?.let {
            holder.changeData(it.elementAt(position).last())
            holder.itemView.setOnClickListener {
                if (listener != null) {
                    listener!!.onItemClick(holder.itemView, holder.adapterPosition)
                }
            }
        }

    }

    override fun getItemCount() = dataSet?.size?:0
}